import axios from "axios"
import qs from "qs"
import {useBackendAccessToken, usePermissions} from "~/composables/state";
import {useLocaleLocation} from "#i18n";
import mime from "mime"
import {v4 as uuid4} from 'uuid'
const makeFormData = (params:any) =>{
    let data = new FormData()
    Object.keys(params).forEach((value) => {
        if(params[value] instanceof Array){
            params[value].forEach((item:any)=>{
                if(item instanceof Array || item instanceof Object){
                    data.append(value + "[]", JSON.stringify(item))
                }else{
                    if(typeof(item) === 'boolean')
                        data.append(value + "[]", item? "1":"0")
                    else
                        data.append(value + "[]", item)
                }
            })
        }else if(params[value] instanceof File){
            data.append(value, params[value])
        }else if(params[value] instanceof Blob){
            data.append( value, new File([params[value]], uuid4().replaceAll("-", "") + `.${mime.getExtension(params[value].type)}`))
        }
        else if(typeof(params[value]) === 'object'){
            data.append(value, JSON.stringify(params[value]))
        }
        else{
            if(typeof(params[value]) === "boolean")
                data.append(value, params[value]? "1":"0")
            else
                data.append(value, params[value]);
        }
    })
    return data;
}

let service = axios.create({
    timeout:50000,
    withCredentials: true,
    baseURL: import.meta.env.VITE_BACKEND_BASE,
})

service.interceptors.request.use(config => {
    return config;
}, error => {
    Promise.reject(error)
})

service.interceptors.response.use(
    response => {
        if (response?.data?.code !== 0) {
            if(response?.data?.code === undefined)
                return response
            return Promise.reject(response.data.message)
        } else {
            return response.data
        }
    }
    , error => {

        if(error.response){
            if (error.response.status === 403) {
                const router = useRouter()
                const backendAccessToken = useBackendAccessToken()
                const permissions = usePermissions()
                const locale_location = useLocaleLocation()
                const cookie = useCookie("backend_access_token")
                cookie.value = null
                backendAccessToken.value = null
                permissions.value = null

                router.push(locale_location("/backend/login"))
                return Promise.reject(error.response.statusText)
                //let first_key = Object.keys(error.response.data.errors)[0]
            } else {
                message.error(error.message)
                return Promise.reject(error.response.statusText)
            }
        }else{
            message.error(error.message)
            return Promise.reject(error.message)
        }
    }
)
export function clientRequest(url:string ,method = 'get', params = {}, header:object = {}, progressCallback = ()=>{})
{
    const access_token = useBackendAccessToken()
    let headers = header
    if(access_token?.value){
        headers["Authorization"] = "Bearer " + access_token.value;
    }
    let met = method.toLowerCase()
    let content = qs.stringify(params)
    let options = {
        url,
        method: met,
        headers,
        progressCallback,
        data: null,
        body: null
    }
    switch (met) {
        case "get":
        case "put":
        case "delete":
            options.url = url + (content.length > 0? "?" + content: "");
            break;
        case "post":
            content = makeFormData(params)
            options.data = content
            break;
        default:
            options.body = content;
            options.headers["Content-Type"] = "application/x-www-form-urlencoded"
            break;
    }
    return service(options);
}
